package com.wangzhixuan.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.easemob.Entry;
import com.wangzhixuan.commons.easemob.model.TalkNode;
import com.wangzhixuan.commons.easemob.service.TalkDataService;
import com.wangzhixuan.commons.shiro.PasswordHash;
import com.wangzhixuan.commons.utils.MethodUtil;
import com.wangzhixuan.commons.utils.PageInfo;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.commons.utils.excel.ExcelUtil;
import com.wangzhixuan.model.Dictionary;
import com.wangzhixuan.model.Role;
import com.wangzhixuan.model.User;
import com.wangzhixuan.model.vo.UserVo;
import com.wangzhixuan.service.IDictionaryService;
import com.wangzhixuan.service.IUserService;

/**
 * @description：用户管理
 * @author：zhixuan.wang
 * @date：2015/10/1 14:51
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordHash passwordHash;
    @Autowired
    private IDictionaryService dictionaryService;

    /**
     * 用户管理页
     *
     * @return
     */
    @GetMapping("/manager")
    public String manager() {
        return "admin/user";
    }

    /**
     * 用户管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(UserVo userVo, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(userVo.getName())) {
            condition.put("name", userVo.getName());
        }
        if (userVo.getCreatedateStart() != null) {
            condition.put("startTime", userVo.getCreatedateStart());
        }
        if (userVo.getCreatedateEnd() != null) {
            condition.put("endTime", userVo.getCreatedateEnd());
        }
        condition.put("companyCode", getCompanyCode());
        pageInfo.setCondition(condition);
        userService.selectDataGrid(pageInfo);
        return pageInfo;
    }

    /**
     * 添加用户页
     *
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/userAdd";
    }

    /**
     * 添加用户
     *
     * @param userVo
     * @return
     * @throws Exception 
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(UserVo userVo) throws Exception {
        List<User> list = userService.selectByLoginName(userVo);
        if (list != null && !list.isEmpty()) {
            return renderError("用户名已存在!");
        }
        String salt = StringUtils.getUUId();
        String pwd = passwordHash.toHex(userVo.getPassword(), salt);
        
     // 先到环信请求注册用户
        TalkDataService service = Entry.getInstance().getTalkApi();
		TalkNode node = new TalkNode();
		node = service.userDrop(userVo.getPhone());
		if (node.getStatusCode() != 200 && node.getStatusCode() != 404) {
			return renderError("添加失败，不能添加到聊天功能!");
		}
		service = Entry.getInstance().getTalkApi();
		node = new TalkNode();
		node = service.userSave(userVo.getPhone(), MethodUtil.MD5(userVo.getPassword()), userVo.getName());
		System.out.println("加密"+MethodUtil.MD5(userVo.getPassword()));
		if (node.getStatusCode() != 200) {
			return renderError("添加失败，不能添加到聊天功能!");
		}
        userVo.setSalt(salt);
        userVo.setPassword(pwd);
        userVo.setCompanyCode(getCompanyCode());
        userService.insertByVo(userVo);
        return renderSuccess("添加成功");
    }
    
/*    	//测试密码用
  		public static void main(String[] args) {
    	String md5 = MethodUtil.MD5("asd24234_ +.;'./，】￥……&……￥@");
    	System.out.println(md5);
	}*/

  		
 
  		
    /**
     * 编辑用户页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
        UserVo userVo = userService.selectVoById(id);
        List<Role> rolesList = userVo.getRolesList();
        List<Long> ids = new ArrayList<Long>();
        for (Role role : rolesList) {
            ids.add(role.getId());
        }
        model.addAttribute("roleIds", ids);
        model.addAttribute("user", userVo);
        return "admin/userEdit";
    }

    /**
     * 编辑用户
     *
     * @param userVo
     * @return
     * @throws Exception 
     */
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(UserVo userVo) throws Exception {
    	System.out.println(userVo.getPassword());
    	if(userVo.getId()==1||userVo.getId()==29||userVo.getId()==30){
    		 return renderError("无法编辑!");
    	}
        List<User> list = userService.selectByLoginName(userVo);
        if (list != null && !list.isEmpty()) {
            return renderError("用户名已存在!");
        }
        
        
        User user = userService.selectById(userVo.getId());
        // 先到环信请求注册用户
        if(StringUtils.isNotBlank(userVo.getPassword())){
        	TalkDataService service = Entry.getInstance().getTalkApi();
    		TalkNode node = new TalkNode();
    		node = service.userDrop(userVo.getPhone());
    		if (node.getStatusCode() != 200 && node.getStatusCode() != 404) {
    			return renderError("添加失败，不能添加到聊天功能!");
    		}
    		//service = Entry.getInstance().getTalkApi();
    		node = new TalkNode();
    		String string = MethodUtil.MD5(userVo.getPassword());
    		node = service.userSave(userVo.getPhone(),string, userVo.getName());
    		if (node.getStatusCode() != 200) {
    			return renderError("添加失败，不能添加到聊天功能!");
    		}
        }
		// 更新密码
        if (StringUtils.isNotBlank(userVo.getPassword())) {
            String salt = user.getSalt();
            String pwd = passwordHash.toHex(userVo.getPassword(), salt);
            userVo.setPassword(pwd);
        }else{
        	userVo.setPassword(user.getPassword());
        }

        userService.updateByVo(userVo);
        return renderSuccess("修改成功！");
    }

/*    public static void main(String[] args) {
		System.out.println(MethodUtil.MD5("1234567"));
	}*/
    /**
     * 修改密码页
     *
     * @return
     */
    @GetMapping("/editPwdPage")
    public String editPwdPage() {
        return "admin/userEditPwd";
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param pwd
     * @return
     * @throws Exception 
     */
    @PostMapping("/editUserPwd")
    @ResponseBody
    public Object editUserPwd(String oldPwd, String pwd) throws Exception {
        User user = userService.selectById(getUserId());
        String salt = user.getSalt();
        if (!user.getPassword().equals(passwordHash.toHex(oldPwd, salt))) {
            return renderError("老密码不正确!");
        }
        TalkDataService service = Entry.getInstance().getTalkApi();
        TalkNode node = new TalkNode();
		node = service.userModifyPassword(user.getPhone(), MethodUtil.MD5(pwd));
		if (node.getStatusCode() != 200) {
			return renderError("添加失败，不能添加到聊天功能!");
		}
        userService.updatePwdByUserId(getUserId(), passwordHash.toHex(pwd, salt));
        return renderSuccess("密码修改成功！");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     * @throws Exception 
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(Long id) throws Exception {
        Long currentUserId = getUserId();
        if (id == 1||id == 29||id==30) {										//1为admin 29为user 20170919
            return renderError("该角色无法删除！");
        }
        if (id == currentUserId) {
            return renderError("不可以删除自己！");
        }
        User user = userService.selectById(id);
        if(user!=null){
        	// 先到环信请求注册用户
        	TalkDataService service = Entry.getInstance().getTalkApi();
        	TalkNode node = new TalkNode();
        	node = service.userDrop(user.getPhone());
        	if (node.getStatusCode() != 200 && node.getStatusCode() != 404) {
        		return renderError("删除失败，聊天功能删除失败!");
        	}
        }
        userService.deleteUserById(id);
        return renderSuccess("删除成功！");
    }
    
    @GetMapping("/gotoImport")
    public String gotoImport() {
        return "admin/import";
    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("/importExcel")
    @ResponseBody
    public Object importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = mulRequest.getFile("myfile");
        String str ="";
        try {
        	Map<String, Object> condition = new HashMap<String, Object>();
        	condition.put("catalogId", "SECTION");
        	condition.put("companyCode", getCompanyCode());
        	List<Map<String, Object>> listSection = dictionaryService.selectSection(condition);
        	condition.put("catalogId", "POST");
        	List<Map<String, Object>> listPost = dictionaryService.selectSection(condition);
        	Map<String,Object> setSection = new HashMap<String,Object>(); 
        	for(Map<String, Object> dictionary : listSection){
        		setSection.put(dictionary.get("dicValue").toString(),(Integer)dictionary.get("id"));
        	}
        	Map<String,Object> setPost = new HashMap<String,Object>(); 
        	for(Map<String, Object> dictionary : listPost){
        		setPost.put(dictionary.get("dicValue").toString(),(Integer)dictionary.get("id"));
        	}
        	User userInfo = null;
        	Dictionary dictionary = null;
            List<User> list =  (List<User>)ExcelUtil.importExcelByIs(file.getInputStream(),User.class);
            for(User u : list){
            	if(!setSection.containsKey(u.getSectionName())){
            		dictionary = new Dictionary();
            		dictionary.setCatalogId("SECTION");
            		dictionary.setDicCode(u.getSectionName());
            		dictionary.setDicValue(u.getSectionName());
            		dictionary.setShowIndex(1);
            		dictionary.setState("1");
            		dictionary.setCompanyCode(getCompanyCode());
            		dictionaryService.insert(dictionary);
            		setSection.put(u.getSectionName(),dictionary.getId());
            	}
            	if(!setPost.containsKey(u.getPostName())){
            		dictionary = new Dictionary();
            		dictionary.setCatalogId("POST");
            		dictionary.setDicCode(u.getPostName());
            		dictionary.setDicValue(u.getPostName());
            		dictionary.setShowIndex(1);
            		dictionary.setState("1");
            		dictionary.setCompanyCode(getCompanyCode());
            		dictionaryService.insert(dictionary);
            		setPost.put(u.getPostName(),dictionary.getId());
            	}
            	userInfo = userService.getUserByPhone(u.getPhone());
            	if(userInfo==null){
            		u.setStatus(0);
            		if (u.getUserTypeName() != null) {
            			if("管理员".equals(u.getUserTypeName())){
            				u.setUserType(0);
            			}else if("操作员".equals(u.getUserTypeName())){				//员工改为操作员
            				u.setUserType(1);
            			}else if("业务员".equals(u.getUserTypeName())){
            				u.setUserType(2);
            			}else if("计划员".equals(u.getUserTypeName())){
            				u.setUserType(3);
            			}else if("拉长".equals(u.getUserTypeName())){
            				u.setUserType(4);
            			}else if("仓管员".equals(u.getUserTypeName())){
            				u.setUserType(5);
            			}else{
            				u.setUserType(6);
            			}
            		}
            		u.setAge(0);
            		if("男".equals(u.getSexName())){
            			u.setSex(1);
            		}else{
            			u.setSex(0);
            		}
            		String salt = StringUtils.getUUId();
                    String pwd = passwordHash.toHex("888888", salt);
                    u.setSalt(salt);
                    u.setPassword(pwd);
                    u.setCompanyCode(getCompanyCode());
                    u.setSectionId((Integer) setSection.get(u.getSectionName()));
                    u.setPostId((Integer) setPost.get(u.getPostName()));
                    u.setCreateTime(new Date());
//            		TalkDataService service = Entry.getInstance().getTalkApi();
//            		service.userSave(u.getPhone(), u.getPassword(),u.getName());
            		
            		// 先到环信请求注册用户
                    TalkDataService service = Entry.getInstance().getTalkApi();
            		TalkNode node = new TalkNode();
            		node = service.userDrop(u.getPhone());
            		if (node.getStatusCode() != 200 && node.getStatusCode() != 404) {
            			return renderError("添加失败，不能添加到聊天功能!");
            		}
            		service = Entry.getInstance().getTalkApi();
            		node = new TalkNode();
            		node = service.userSave(u.getPhone(), MethodUtil.MD5("888888"), u.getName());
            		if (node.getStatusCode() != 200) {
            			return renderError("添加失败，不能添加到聊天功能!");
            		}
            		userService.insert(u);
            	}else{
            		str = str +u.getPhone() +",";
            	}
            }
            if(!"".equals(str)){
            	str = str.substring(0,str.length()-1);
            	return renderSuccess( "文件导入成功！,手机号为"+str+"已存在，无需导入");
            }else{
            	return renderSuccess( "文件导入成功！");
            }
        } catch (Exception e) {
        	logger.error(e.getLocalizedMessage());
        	return renderError("文件导入失败，请检查数据的合法性！");
        }
    }
}
